package com.mca.framework.completableFuture;

import java.util.concurrent.*;

/**
 * @Author: zhoupeng
 * @createTime: 2025年07月07日 21:56:25
 * @version: 1.0
 * @Description:
 * @copyright:
 */
public class HandleDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        //handleAsync 则用来表示，线程出现错误，获取错误信息，并返回结果，
        // 场景： 可以用来多线程调用接口，如果报错了，就记录失败状态，还有信息，后期在通过定时任务补偿
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
           //子任务
//            int i=1/0;
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 123;
        }, executorService).handleAsync((value,throwable) ->{
            int result  =1;
            if (throwable == null){
                //代表前置任务执行没有出现异常
                result = value*10;
                System.out.println(result);
            }else {
                //前置任务执行出现异常
                System.out.println(throwable.getMessage());
            }

            return result;
        },executorService);

        //主任务
        System.out.println("main end ");

        //获取子任务结果
        try {
            Integer value = future.get();
            System.out.println(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executorService.shutdown();

    }
}
